#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ThreadPool.hpp"
#include "netaddr.hpp"

using namespace std;

// using scfunc_t = function<string(string &)>;
using scfunc_t = function<void()>;

class Server
{
private:
    void CheckUser(netaddr user)
    {
        SmartMutex smartmutex(&_user_mutex);
        for (auto _user : _users)
        {
            if (_user == user)
            {
                return;
            }
        }
        _users.push_back(user);
        LOG(Debug, "%s online\n", user.SockInfo().c_str());
    }

    void Route(netaddr &addr, const string &msg)
    {
        SmartMutex smartmutex(&_user_mutex);

        string ret = "[";
        ret += addr.SockInfo();
        ret += "]";
        ret += "# ";
        ret += msg;


        for (auto user : _users)
        {
            if (user != addr)
            {
                int n = sendto(_sockfd, ret.c_str(), ret.size(), 0, (struct sockaddr *)&user.GetAddr(), sizeof(user.GetAddr()));
                LOG(Debug, "%s send message# %s\n", user.SockInfo().c_str(), msg.c_str());            
            }
        }
    }

public:
    Server(uint16_t port) : _port(port)
    {
        pthread_mutex_init(&_user_mutex, nullptr);
    }

    void Init()
    {
        // 创建网络文件信息
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            exit(1);
        }

        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        // addr.sin_addr.s_addr = inet_addr(_ip.c_str());
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_port = htons(_port);
        addr.sin_family = AF_INET;

        int n = bind(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (n < 0)
        {
            exit(2);
        }

        _tp.Start();
    }

    void Start()
    {
        for (;;)
        {
            char buffer[1024];
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);
            // 接收客户端消息
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&addr, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                netaddr user(addr);

                CheckUser(user);
                string msg = buffer;
                scfunc_t func = bind(&Server::Route, this, user, msg);
                _tp.Push(func);
            }
        }

        close(_sockfd);
    }

    ~Server()
    {
        pthread_mutex_destroy(&_user_mutex);
    }

private:
    int _sockfd;
    // scfunc_t _Response;
    uint16_t _port;

    ThreadPool<scfunc_t> _tp;
    vector<netaddr> _users;
    pthread_mutex_t _user_mutex;
};